

var proportion = 1  // 比例

// 设置的宽高
var canvasW = 0
var canvasH = 0

// 最终呈现页面的大小（缩放后大小）
var sCanvasW = 0
var sCanvasH = 0

// 背景画布
var canvas = null;
var ctx = null;

// 图片画布
var imgCanvas = null
var imgCtx = null

// 鼠标拖动以及图片偏移量
var isDragging = false;
var startDragX = null;
var startDragY = null;

// 图片位置
var imgX = 0
var imgY = 0

const image = new Image();
const backImg = new Image();

image.onload = function() {
  // 隐藏加载中遮罩
  $("#mask").hidden = true
}

/**
 * 初始化钩子
*/
window.onload = function() {
  init()
  changeSizeEvent()
  initPhoto()  // 初始化照片
}


/**
 * 初始化
 */
function init() {

  image.src = $("#photo").src
  
  canvasW = $("#canvasW").value
  canvasH = $("#canvasH").value

  // 最终呈现页面的大小
  sCanvasW = canvasW * proportion
  sCanvasH = canvasH * proportion

  canvas = $("#canvas");
  ctx = canvas.getContext("2d");

  imgCanvas = $("#imgCanvas")
  imgCtx = imgCanvas.getContext('2d');


  // 鼠标事件处理
  imgCanvas.addEventListener('mousedown', function(e) {
    isDragging = true;
    startDragX = e.clientX;
    startDragY = e.clientY;   
    imgCanvas.style.cursor = 'grabbing'
  })

  /**
   * 释放移动事件
   */
  function removeRelease() {
    isDragging = false;
    imgCanvas.style.cursor = 'grab'
  }
  imgCanvas.addEventListener("mouseup", removeRelease)
  imgCanvas.addEventListener("mouseout", removeRelease)


  imgCanvas.addEventListener("mousemove", function(e) {
    if (isDragging) {
      // console.log(e.clientX, e.clientY)
      var mouseX = e.clientX - startDragX;
      var mouseY = e.clientY - startDragY;
      imgX += mouseX
      imgY += mouseY
      requestAnimationFrame(rendeImage)

      startDragX = e.clientX;
      startDragY = e.clientY;   

    }

  })
}


// 视口大小改变
window.onresize = function() {
  setCanvasScale()
}


/**
 * 根据视口大小调整缩放画布，自适应屏幕
*/
function setCanvasScale() {
  // 计算视口可用宽高（保留10%）
  const windowW = (window.innerWidth - 40) * 0.9
  const windowH = window.innerHeight * 0.9

  // 换算缩放前的偏移位置
  let $imgX = imgX / proportion
  let $imgY = imgY / proportion

  // 计算宽高比例
  proportion = Math.min.apply(Math, [(windowW / canvasW), (windowH / canvasH)])
  document.getElementById("proportion").innerHTML = (proportion * 100 ).toFixed(2)

  sCanvasW = proportion * canvasW
  sCanvasH = proportion * canvasH

  // 调整canvas视图大小
  canvas.style.width = sCanvasW + 'px'
  canvas.style.height = sCanvasH + 'px'
  imgCanvas.style.width = sCanvasW + 'px'
  imgCanvas.style.height = sCanvasH + 'px'

  // 根据新的缩放调整偏移
  imgX = ($imgX * proportion)
  imgY = ($imgY * proportion)

  return {
    width: sCanvasW, 
    height: sCanvasH
  }
}


/**
 * 宽高交换事件
 */
function exchangeEvent() {
  $("#canvasW").value = canvasH
  $("#canvasH").value = canvasW
  changeSizeEvent()
}


/**
 * 设置背景图片事件
 */
function setBackgrountImage() {
  backImg.src = URL.createObjectURL($("#backImg").files[0])
  console.log("backImg", $("#backImg").files[0])
  backImg.onload = function() {
    ctx.drawImage(backImg, 0, 0, canvasW, canvasH)
  }
}

// 修改颜色
function switchColorEvent() {
  const col = document.getElementById('switchColor').value;
  ctx.fillStyle = col;
  ctx.fillRect(0, 0, canvasW, canvasH);
}

// 保存图片
function exportImgEvent() {

  let saveCanvas = document.createElement('canvas')
  saveCanvas.width = canvasW
  saveCanvas.height = canvasH
  let $ctx = saveCanvas.getContext('2d')

  $ctx.drawImage(canvas, 0, 0)
  $ctx.drawImage(imgCanvas, 0, 0)
  console.log("--", saveCanvas)

  const imgData = saveCanvas.toDataURL("image/jpg");
  let a = document.createElement('a')
  a.href = imgData
  a.download = 'image.jpg'
  a.click()
  // 移除虚拟链接
  // document.body.removeChild(a);
}

// 照片比例事件监听
function photoScaleEvent() {
  const photoScale = document.getElementById("photoScale").value
  initPhoto()
}

/**
 * 修改尺寸事件监听
 */
function changeSizeEvent(unchanged=false) {

  let $canvasW = $("#canvasW").value
  let $canvasH = $("#canvasH").value
  if ( !$canvasW || $canvasW <= 0 || !$canvasH || $canvasH <= 0 ) return

  canvasW = $canvasW
  canvasH = $canvasH
  
  // 重置画布内容
  scale = setCanvasScale()  // 获取缩放后的大小

  // 调整canvas实际大小 和 视图大小
  canvas.width = canvasW
  canvas.height = canvasH

  imgCanvas.width = canvasW
  imgCanvas.height = canvasH

  // 调整画布大小后，样式会失效，需要重新调整
  if ($("#backImg").value) {
    // 重新渲染背景
    ctx.drawImage(backImg, 0, 0, canvasW, canvasH)
  } else {
    // 重新渲染颜色
    ctx.fillStyle = $("#switchColor").value;
    ctx.fillRect(0, 0, canvasW, canvasH);
  }

  // 重置照片位置
  initPhoto(false, unchanged)
}



/**
 * 初始化照片
 * ignore: 关闭自动重置仍然可重置，true时关闭自动重置仍可重置
 * unchanged: 强制关闭修改，ture时任何参数都不会影响位置
*/
function initPhoto(ignore=false, unchanged=false) {
  // console.log('0', $("#autoResetPP").checked)
  if (!unchanged && ($("#autoResetPP").checked || ignore)) {
    const photo = $("#photo")
    let ps = $("#photoScale").value / 100
    imgX = (sCanvasW - photo.width * ps * proportion) / 2 + 5
    imgY = (sCanvasH - photo.height * ps * proportion)
  }

  rendeImage()
}


/**
 * 渲染图片到画布
*/
function rendeImage(){
  // 清空Canvas
  imgCtx.clearRect(0, 0, imgCanvas.width, imgCanvas.height);
  
  photoScale = $("#photoScale").value / 100
  imgCtx.drawImage(
    image, 
    imgX / proportion, 
    imgY / proportion, 
    image.width * photoScale, 
    image.height * photoScale
  )
}


// 自定义的获取dom的方法
function $(attrName) {
  attr = attrName.substr(0, 1)
  aName = attrName.substr(1)
  if (attr === '#') {
    return document.getElementById(aName)
  }else if (attr === '.') {
    return document.getElementsByClassName(aName)
  }
  console.log("传入参数错误");
}

